package com.example.design.beautiful.unit_test.performance_counter.aggregator;

import com.example.design.beautiful.unit_test.performance_counter.collector.RequestInfo;

import java.util.Collections;
import java.util.List;

public class Aggregator {
  public static RequestStat aggregate(List<RequestInfo> requestInfos, long durationInMillis) {
    double maxRespTime = Double.MIN_VALUE;
    double minRespTime = Double.MAX_VALUE;
    double avgRespTime = -1;
    double p999RespTime = -1;
    double p99RespTime = -1;
    double sumRespTime = 0;
    long count = 0;
    for (RequestInfo requestInfo : requestInfos) {
      // 次数
      ++count;
      double respTime = requestInfo.getResponseTime();

      // 最大响应时间
      if (maxRespTime < respTime) {
        maxRespTime = respTime;
      }

      // 最小响应时间
      if (minRespTime > respTime) {
        minRespTime = respTime;
      }

      // 总响应时间
      sumRespTime += respTime;
    }

    // 平均响应时间
    if (count != 0) {
      avgRespTime = sumRespTime / count;
    }

    // tps
    long tps = count / durationInMillis * 1000;

    // 排序
    Collections.sort(requestInfos, (o1, o2) -> {
      double diff = o1.getResponseTime() - o2.getResponseTime();
      if (diff < 0.0) {
        return -1;
      } else if (diff > 0.0) {
        return 1;
      } else {
        return 0;
      }
    });

    int idx999 = (int)(count * 0.999);
    int idx99 = (int)(count * 0.99);
    if (count != 0) {
      // 99.9 百分位值
      p999RespTime = requestInfos.get(idx999).getResponseTime();
      // 99 百分位值
      p99RespTime = requestInfos.get(idx99).getResponseTime();
    }
    RequestStat requestStat = new RequestStat();
    requestStat.setMaxResponseTime(maxRespTime);
    requestStat.setMinResponseTime(minRespTime);
    requestStat.setAvgResponseTime(avgRespTime);
    requestStat.setP999ResponseTime(p999RespTime);
    requestStat.setP99ResponseTime(p99RespTime);
    requestStat.setCount(count);
    requestStat.setTps(tps);
    return requestStat;
  }
}

